package com.kkw.shoppingmall.member.interceptor;

import com.kkw.common.constant.AuthServerConstant;
import com.kkw.common.vo.MemberResVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Kevin
 * @date 2021-06-13
 **/
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    //ThreadLocal 同一线程上信息共享
    public static ThreadLocal<MemberResVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决库存调用订单服务 失败的问题
        String uri = request.getRequestURI();

        //这里如果不放行的话 认证fegin调用member的服务是不会成功的会报异常

        // 那里也会不成功调用 java.net.HttpRetryException: cannot retry due to redirection, in streaming mode
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match){
            return true;
        }

        HttpSession session = request.getSession();
        MemberResVo attribute = (MemberResVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            //说明登录了 放行
            loginUser.set(attribute);
            return true;
        } else {
            //没登录 去登录页 来拦截
            session.setAttribute("msg", "请先登录～～");
            response.sendRedirect("http://auth.shoppingmall.com/login.html");
            return false;
        }
    }
}
